﻿using System;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Castle.MicroKernel;
using Castle.Windsor;

namespace SPE.Core.Factories
{
    public class WindsorControllerFactory : DefaultControllerFactory
    {
        private readonly IWindsorContainer _container;

        public WindsorControllerFactory(IWindsorContainer container)
        {
            if (container == null)
            {
                throw new ArgumentNullException();
            }

            _container = container;
        }

        protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
        {
            if (controllerType == null)
            {
                throw new HttpException();
            }

            if (!typeof(IController).IsAssignableFrom(controllerType))
            {
                throw new ArgumentException();
            }

            try
            {
                return (IController)_container.Resolve(controllerType);
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException();
            }
        }

        public override void ReleaseController(IController controller)
        {
            IDisposable disposable = controller as IDisposable;

            if (disposable != null)
            {
                disposable.Dispose();
            }

            _container.Release(controller);
        }
    }
}
